import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'
import createItemTip from './topbarTip.jsx'
import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,propConfig,parseToTopbar} from '../apis/core-util'

export default class MainScope extends Scope {
  constructor(){
    super();
    this.viewType = 'domain';
    this.$state = {
      topbar:{
        $id:'topbar1',
        loading:true
      },
      sortOptions:[{
        key:'domain',
        label:'域名'
      },{
        key:'statuscode',
        label:'状态码'
      },{
        key:'errorcode',
        label:'故障类型'
      }]
    };
    this.topbarApi = coreApi({
      limit:20,
      urlName:'errorrate',
      viewKey:'error_rate',
      size:1
    },TimeStore.getValue,function(){
      if (this.viewType === 'errorcode') {
        return {
          classify:this.viewType,
          errorcode:0
        }
      } else {
        return {
          classify:this.viewType,
          statusCode:400
        };
      }
    }.bind(this),function (){
      return {order:sortMap[this.viewKey]}
    });
  }
  fetch(){
    var _this = this
    this.topbarApi.fetch().then((data,params) => {
      var list = parseToTopbar(data,params)
      var dataWithErrorCount = _(list).chain().map((item) => _.extend({},item,{tip:createItemTip(item)})).value()
      _this.$state.topbar = {
        data:dataWithErrorCount
      }
    },(err) => {
      _this.$state.topbar = {
        error:err
      }
    },(params) => {
      _this.$state.topbar = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(() => {
      _this.emit()
    })
  }
  $settime(payload){
    this.fetch()
  }
  $changesort(payload){
    this.viewType = payload.key;
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
